package de.tc.stammdatenverwaltung.functions;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import javax.swing.JOptionPane;

public class PropertiesHandler{

  private char[] password = new char[]
    {
      'F', 'T', 'C', '_', 's', 't', 'a', 'm', 'm', 'd', 'a', 't', 'e', 'n', '$', '%', '#', '0', '8', '/', '1', '5'
    };


  public String propertiesFile = 
          System.getProperty("user.dir") + System.getProperty("file.separator") + "stammdaten.properties";
  public Properties p = new Properties();

  public PropertiesHandler() {
    this.getProperties();
  }

  public Properties getProperties()
  {
    try
    {
      p.load(new FileInputStream(propertiesFile) );
      return p;
    }
    catch (IOException e)
    {
      JOptionPane.showMessageDialog(null, "Das Laden der Config-Datei " + propertiesFile +
        " ist fehlgeschlagen\r\n" + e.getLocalizedMessage(), "Fehler!", 1);
      e.printStackTrace();
    }
    return null;
  }

  public String getProperty(String keyName)
  {
    if ( keyName.contains("pass") )
      return decryptString( p.getProperty( keyName, "") );
    else
      return p.getProperty( keyName, "");
  }

  public void setProperty(String keyName, String value)
  {
    if ( keyName.contains("pass") )
      p.setProperty(keyName, encryptString(value) );
    else
      p.setProperty(keyName, value);
  }

  private String encryptString(String s)
  {
    EncWrapper crypter = new EncWrapper( new String(password) );
    return crypter.encrypt(s);
  }

  private String decryptString(String s)
  {
    EncWrapper crypter = new EncWrapper( new String(password) );
    return crypter.decrypt(s);
  }


  public void setProperties()
  {
    try
    {
      p.store(new FileOutputStream(propertiesFile), null);
    }
    catch (FileNotFoundException ex)
    {
      JOptionPane.showMessageDialog(null, "Das Schreiben der Config-Datei nach " +
        propertiesFile + " ist fehlgeschlagen\r\n" + ex.getLocalizedMessage(),
              "Fehler!", 1);
      ex.printStackTrace();
    }
    catch (IOException ex)
    {
      JOptionPane.showMessageDialog(null, "Das Schreiben der Config-Datei nach " +
        propertiesFile + " ist fehlgeschlagen\r\n" + ex.getLocalizedMessage(),
              "Fehler!", 1);
      ex.printStackTrace();
    }
  }

  @Override
  public void finalize()
  {
    if ( !p.isEmpty() )
      this.setProperties();
  }
}
